<?php
/**
 * Created by PhpStorm.
 * User: yuanjie
 * Date: 15/9/9
 * Time: 下午4:06
 */
class WxwUserController extends BaseController {

    const USER_STATUS_NORMAL = 1; //用户状态 1 正常
    const USER_STATUS_FROZEN = 2; //用户状态 2 冻结

    /*
     * test
     * */
    public function test(){
        $a = Sms::send('18610550696','员工您好，感谢您对此次测试的配合。',1);
        var_dump($a->body);
        $result = substr($a->body,74,strlen($a->body) - 74 - 9);
        var_dump($result);
        exit;
    }

    /*
     * 服务器保存用户session
     * */
    public function session_set(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'data' => 'required',
            )
        );

        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            if ($validator->fails()) {
                $response = Lang::get("error.user_login_args_error_1011");
                break;
            }

            //传入参数
            $token = Input::get('token');
            $data = Input::get('data');
            //验证token
            $user_data = Users::getUserByToken($token);
            if(is_numeric($user_data) && $user_data < 0){
                $response = Lang::get("error.user_token_not_exist_1004");
                break;
            }
            //保存用户session
            $redis = Redis::connection();
            $redis->set($token, $data);
            $redis->expire($token, Config::get("user.session_time_out"));
            Redis::disconnect();
            $result = array(
                'session_time_out' => Config::get("user.session_time_out"),
            );
            $response = array('code' => 0, 'msg' => 'ok', 'result' => $result);
        } while (false);
        Log::info("info", array("system" => "wxw" ,"event" => "session_set", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

    /*
     * 服务器返回保存的用户session
     * */
    public function session_get(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
            )
        );

        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            if ($validator->fails()) {
                $response = Lang::get("error.user_login_args_error_1011");
                break;
            }

            //传入参数
            $token = Input::get('token');
            //验证token
            $user_data = Users::getUserByToken($token);
            if(is_numeric($user_data) && $user_data < 0){
                $response = Lang::get("error.user_token_not_exist_1004");
                break;
            }
            //获取用户session
            $redis = Redis::connection();
            $data = $redis->get($token);
            Redis::disconnect();

            $result = array(
                'data' => $data
            );
            $response = array('code' => 0, 'msg' => 'ok', 'result' => $result);

        } while (false);
        Log::info("info", array("system" => "wxw" ,"event" => "session_get", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

    /*
     * 用户常用地址列表
     * */
    public function address_list(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
            )
        );

        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            if ($validator->fails()) {
                $response = Lang::get("error.user_login_args_error_1011");
                break;
            }

            //传入参数
            $token = Input::get('token');

            //验证token
            $user_data = Users::getUserByToken($token);
            if(is_numeric($user_data) && $user_data < 0){
                $response = Lang::get("error.user_token_not_exist_1004");
                break;
            }

            //获取用户常用地址列表
            $address_list = UserAddressInfo::where('user_id',$user_data->id)
                ->where('status',1)
                ->select(array('id','name','phone','is_default','city','province','country','address','post_code'))
                ->orderBy('updated_at', 'asc')
                ->get()->toArray();
            $count = count($address_list);
            $result = array(
                'count' => $count,
                'address_list' => $address_list
            );
            $response = array('code' => 0, 'msg' => 'ok', 'result' => $result);


        } while (false);
        Log::info("info", array("system" => "wxw" ,"event" => "address_list", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

    /*
     * 用户添加常用地址
     * */
    public function address_add(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'name' => 'required',
                'phone' => 'required',
                'is_default' => 'required',
                'city' => 'required',
                'province' => 'required',
                'country' => 'required',
                'address' => 'required',
                'post_code' => 'required',
            )
        );

        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            if ($validator->fails()) {
                $response = Lang::get("error.user_login_args_error_1011");
                break;
            }

            //传入参数
            $token = Input::get('token');
            $name = Input::get('name');
            $phone = Input::get('phone');
            $is_default = Input::get('is_default');
            $city = Input::get('city');
            $province = Input::get('province');
            $country = Input::get('country');
            $address = Input::get('address');
            $post_code = Input::get('post_code');

            //验证token
            $user_data = Users::getUserByToken($token);
            if(is_numeric($user_data) && $user_data < 0){
                $response = Lang::get("error.user_token_not_exist_1004");
                break;
            }

            //记录用户常用地址信息
            try{
                if($is_default == 1){
                    UserAddressInfo::where('user_id',$user_data->id)
                        ->where('status',1)
                        ->update(array('is_default' => 0));
                }
                $address_data = new UserAddressInfo;
                $address_data->user_id = $user_data->id;
                $address_data->status = 1;
                $address_data->name = $name;
                $address_data->phone = $phone;
                $address_data->is_default = $is_default;
                $address_data->city = $city;
                $address_data->province = $province;
                $address_data->country = $country;
                $address_data->address = $address;
                $address_data->post_code = $post_code;
                $address_data->save();

                $response = array('code' => 0, 'msg' => 'ok', 'result' => array('address_id' => $address_data->id));
            } catch (Exception $e) {
                Log::error("error", array("system" => "wxw" ,"event" => "address_add", 'input' =>Input::all() ,"exception" => $e));
                $response = Lang::get("error.user_address_add_error_1010");
                break;
            }
        } while (false);
        Log::info("info", array("system" => "wxw" ,"event" => "address_add", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

    /*
     * 用户修改常用地址
     * */
    public function address_mod(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'address_id' => 'required',
                'name' => 'required',
                'phone' => 'required',
                'is_default' => 'required',
                'city' => 'required',
                'province' => 'required',
                'country' => 'required',
                'address' => 'required',
                'post_code' => 'required',
            )
        );

        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            if ($validator->fails()) {
                $response = Lang::get("error.user_login_args_error_1011");
                break;
            }

            //传入参数
            $token = Input::get('token');
            $id = Input::get('address_id');
            $name = Input::get('name');
            $phone = Input::get('phone');
            $is_default = Input::get('is_default');
            $city = Input::get('city');
            $province = Input::get('province');
            $country = Input::get('country');
            $address = Input::get('address');
            $post_code = Input::get('post_code');

            //验证token
            $user_data = Users::getUserByToken($token);
            if(is_numeric($user_data) && $user_data < 0){
                $response = Lang::get("error.user_token_not_exist_1004");
                break;
            }

            //更新用户常用地址信息
            try{
                if($is_default == 1){
                    UserAddressInfo::where('user_id',$user_data->id)
                        ->where('status',1)
                        ->update(array('is_default' => 0));
                }
                UserAddressInfo::where('user_id',$user_data->id)
                    ->where('status',1)
                    ->where('id',$id)
                    ->update(array(
                        'name' =>$name ,
                        'phone' => $phone ,
                        'is_default' => $is_default ,
                        'city' => $city ,
                        'province' => $province,
                        'country' => $country,
                        'address' => $address,
                        'post_code' => $post_code
                    ));
                $response = array('code' => 0, 'msg' => 'ok', 'result' => array('address_id' => $id));
            } catch (Exception $e) {
                Log::error("error", array("system" => "wxw" ,"event" => "car_mod", 'input' =>Input::all() ,"exception" => $e));
                $response = Lang::get("error.user_address_mod_error_1017");
                break;
            }
        } while (false);
        Log::info("info", array("system" => "wxw" ,"event" => "car_mod", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

    /*
     * 用户删除常用地址
     * */
    public function address_del(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'address_id' => 'required',
            )
        );

        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            if ($validator->fails()) {
                $response = Lang::get("error.user_login_args_error_1011");
                break;
            }

            //传入参数
            $token = Input::get('token');
            $id = Input::get('address_id');

            //验证token
            $user_data = Users::getUserByToken($token);
            if(is_numeric($user_data) && $user_data < 0){
                $response = Lang::get("error.user_token_not_exist_1004");
                break;
            }

            //更新用户常用地址信息
            try{
                UserAddressInfo::where('user_id',$user_data->id)
                    ->where('status',1)
                    ->where('id',$id)
                    ->delete();
                $response = array('code' => 0, 'msg' => 'ok', 'result' => array('address_id' => $id));
            } catch (Exception $e) {
                Log::error("error", array("system" => "wxw" ,"event" => "car_del", 'input' =>Input::all() ,"exception" => $e));
                $response = Lang::get("error.user_car_del_error_1009");
                break;
            }
        } while (false);
        Log::info("info", array("system" => "wxw" ,"event" => "car_del", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

    /*
     * 用户车辆列表
     * 锁定的车辆通过界面控制，不可以修改和删除
     * */
    public function car_list(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
            )
        );

        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            if ($validator->fails()) {
                $response = Lang::get("error.user_login_args_error_1011");
                break;
            }

            //传入参数
            $token = Input::get('token');

            //验证token
            $user_data = Users::getUserByToken($token);
            if(is_numeric($user_data) && $user_data < 0){
                $response = Lang::get("error.user_token_not_exist_1004");
                break;
            }

            //获取用户车辆列表
            $car_list = UserCarInfo::leftJoin('car_series_type', 'user_car_info.car_series_id', '=', 'car_series_type.id')
                ->where('user_car_info.user_id',$user_data->id)
                ->where('user_car_info.status',1)
                ->where('car_series_type.status',1)
                ->select(array('user_car_info.id','user_car_info.car_brand_id','user_car_info.car_series_id','user_car_info.car_model_id','user_car_info.is_default','user_car_info.is_lock','car_series_type.name','car_series_type.icon'))
                ->orderBy('user_car_info.updated_at', 'asc')
                ->get()->toArray();
            $count = count($car_list);
            $result = array(
                'count' => $count,
                'car_list' => $car_list
            );
            $response = array('code' => 0, 'msg' => 'ok', 'result' => $result);


        } while (false);
        Log::info("info", array("system" => "wxw" ,"event" => "list_car", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

    /*
     * 用户添加车辆
     * */
    public function car_add(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'car_brand_id' => 'required',
                'car_series_id' => 'required',
                'car_model_id' => 'required',
                'is_default' => 'required',
            )
        );

        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            if ($validator->fails()) {
                $response = Lang::get("error.user_login_args_error_1011");
                break;
            }

            //传入参数
            $token = Input::get('token');
            $car_brand_id = Input::get('car_brand_id');
            $car_series_id = Input::get('car_series_id');
            $car_model_id = Input::get('car_model_id');
            $is_default = Input::get('is_default');

            //验证token
            $user_data = Users::getUserByToken($token);
            if(is_numeric($user_data) && $user_data < 0){
                $response = Lang::get("error.user_token_not_exist_1004");
                break;
            }

            //记录用户车辆信息
            try{
                if($is_default == 1){
                    UserCarInfo::where('user_id',$user_data->id)
                        ->where('status',1)
                        ->update(array('is_default' => 0));
                }
                $car_data = new UserCarInfo;
                $car_data->user_id = $user_data->id;
                $car_data->car_brand_id = $car_brand_id;
                $car_data->car_series_id = $car_series_id;
                $car_data->car_model_id = $car_model_id;
                $car_data->is_default = $is_default;
                $car_data->status = 1;
                $car_data->save();
                $response = array('code' => 0, 'msg' => 'ok', 'result' => array('car_id' => $car_data->id));
            } catch (Exception $e) {
                Log::error("error", array("system" => "wxw" ,"event" => "car_add", 'input' =>Input::all() ,"exception" => $e));
                $response = Lang::get("error.user_car_add_error_1006");
                break;
            }
        } while (false);
        Log::info("info", array("system" => "wxw" ,"event" => "car_add", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

    /*
     * 用户修改车辆
     * */
    public function car_mod(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'car_id' => 'required',
                'car_brand_id' => 'required',
                'car_series_id' => 'required',
                'car_model_id' => 'required',
                'is_default' => 'required',
            )
        );

        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            if ($validator->fails()) {
                $response = Lang::get("error.user_login_args_error_1011");
                break;
            }

            //传入参数
            $token = Input::get('token');
            $id = Input::get('car_id');
            $car_brand_id = Input::get('car_brand_id');
            $car_series_id = Input::get('car_series_id');
            $car_model_id = Input::get('car_model_id');
            $is_default = Input::get('is_default');

            //验证token
            $user_data = Users::getUserByToken($token);
            if(is_numeric($user_data) && $user_data < 0){
                $response = Lang::get("error.user_token_not_exist_1004");
                break;
            }

            //更新用户车辆信息
            try{
                $car_data = UserCarInfo::where('user_id',$user_data->id)
                    ->where('status',1)
                    ->where('id',$id)
                    ->first();
                if($car_data->is_lock == 1){
                    $response = Lang::get("error.user_car_system_lock_1007");
                    break;
                }

                if($is_default == 1){
                    UserCarInfo::where('user_id',$user_data->id)
                        ->where('status',1)
                        ->update(array('is_default' => 0));
                }

                UserCarInfo::where('user_id',$user_data->id)
                    ->where('status',1)
                    ->where('id',$id)
                    ->update(array('car_brand_id' =>$car_brand_id , 'car_series_id' => $car_series_id ,'car_model_id' => $car_model_id ,'is_default' => $is_default));
                $response = array('code' => 0, 'msg' => 'ok', 'result' => array('car_id' => $id));
            } catch (Exception $e) {
                Log::error("error", array("system" => "wxw" ,"event" => "car_mod", 'input' =>Input::all() ,"exception" => $e));
                $response = Lang::get("error.user_car_mod_error_1008");
                break;
            }
        } while (false);
        Log::info("info", array("system" => "wxw" ,"event" => "car_mod", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

    /*
     * 用户删除车辆
     * */
    public function car_del(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'car_id' => 'required',
            )
        );

        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            if ($validator->fails()) {
                $response = Lang::get("error.user_login_args_error_1011");
                break;
            }

            //传入参数
            $token = Input::get('token');
            $id = Input::get('car_id');

            //验证token
            $user_data = Users::getUserByToken($token);
            if(is_numeric($user_data) && $user_data < 0){
                $response = Lang::get("error.user_token_not_exist_1004");
                break;
            }

            //更新用户车辆信息
            try{
                $car_data = UserCarInfo::where('user_id',$user_data->id)
                    ->where('status',1)
                    ->where('id',$id)
                    ->first();
                if($car_data->is_lock == 1){
                    $response = Lang::get("error.user_car_system_lock_1007");
                    break;
                }

                UserCarInfo::where('user_id',$user_data->id)
                    ->where('status',1)
                    ->where('id',$id)
                    ->delete();
                $response = array('code' => 0, 'msg' => 'ok', 'result' => array('car_id' => $id));
            } catch (Exception $e) {
                Log::error("error", array("system" => "wxw" ,"event" => "car_del", 'input' =>Input::all() ,"exception" => $e));
                $response = Lang::get("error.user_car_del_error_1009");
                break;
            }
        } while (false);
        Log::info("info", array("system" => "wxw" ,"event" => "car_del", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

    /*
     * 用户注册
     *
     * */
    public function user_login(){
        $validator = Validator::make(Input::all(),
            array(
                'phone' => 'required',
//                'area' => 'required',
                'check_code' => 'required',
            )
        );

        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            if ($validator->fails()) {
                $response = Lang::get("error.user_login_args_error_1011");
                break;
            }

            //传入参数
            $phone = Input::get('phone');
            //todo default area for test
            $area = '010';
            $check_code = Input::get('check_code');
            $source_id = Input::get('source_id')?Input::get('source_id'):Config::get('user.user_source_weixin');

            //判断验证码是否存在
            $record = UserCheckCode::getCheckCode($phone,$area);
            if(is_null($record)){ //没有记录
                $response = Lang::get("error.user_login_checkcode_null_1012");
                break;
            }
            //校验是否超过时限
            if( time() > Common::datetime2Num($record->out_time_at) ){
                $response = Lang::get("error.user_login_checkcode_timeout_1013");
                break;
            }

            //校验验证码是否匹配
            if($record->check_code != $check_code){
                $response = Lang::get("error.user_login_checkcode_error_1014");
                break;
            }

            //判断用户是否存在
            $user_data = Users::getUser($area,$phone);
            if(is_null($user_data)){ //新用户
                try {
                    $user_data = new Users;
                    $user_data->phone = $phone;
                    $user_data->area = $area;
                    $user_data->status = WxwUserController::USER_STATUS_NORMAL;
                    $user_data->register_source_id = $source_id;
                    $user_data->created_at = Common::num2DateTime(time());
                    $user_data->member = Config::get('user.def_member');
                    $user_data->save();
                } catch (Exception $e) {
                    Log::error("error", array("system" => "wxw" ,"event" => "user_login", 'input' =>Input::all() ,"exception" => $e));
                    $response = Lang::get("error.user_create_new_error_1015");
                    break;
                }
            }

            //todo 根据用户的注册来源补充用户附加信息

            //记录用户token，到数据库
            try {
                UserTokens::where('user_id',$user_data->id)->delete();
                $user_token = new UserTokens;
                $user_token->user_id = $user_data->id;
                $user_token->token = md5($phone.time().rand(0,100));
                $user_token->created_at = Common::num2DateTime(time());
                $user_token->out_time_at = Common::num2DateTime(time() + Config::get("user.token_time_out"));
                $user_token->save();
            } catch (Exception $e) {
                Log::error("error", array("system" => "wxw" ,"event" => "user_login", 'input' =>Input::all() ,"exception" => $e));
                $response = Lang::get("error.user_token_save_error_1016");
                break;
            }

            //组织返回
            $response = array(
                'code' => 0,
                'msg' => 'ok',
                'result' => array(
                    'token' => $user_token->token,
                    'expired' => $user_token->out_time_at
                ));

        } while (false);
        Log::info("info", array("system" => "wxw" ,"event" => "user_login", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

    /*
     * 用户申请短信验证码
     *
     * */
    public function sms_check_code()
    {
        $validator = Validator::make(Input::all(),
            array(
                'phone' => 'required',
//                'area' => 'required',
            )
        );

        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            if ($validator->fails()) {
                $response = Lang::get("error.user_sms_check_code_args_error_1001");
                break;
            }
            //获取手机号
            $phone = Input::get('phone');
            //todo default area for test
            $area = '010';
//            $area = Input::get('area');
            $time_out_default = Config::get("user.check_code_time_out");


            //检查手机号是否下发验证码
            $record = UserCheckCode::getCheckCode($phone,$area);
            if(!is_null($record)){ //有记录
                //判断是否超时
                if( time() < Common::datetime2Num($record->out_time_at) ){ //没有超过时限
                    $response = array(
                        'code' => 0,
                        'msg' => 'ok',
                        'result' => array(
                            'out_time' => Common::datetime2Num($record->out_time_at) - time(),
                            'check_code' => $record->check_code // todo 调试使用
                        ));
                    break;
                }else{ //超过限时
                    UserCheckCode::delCheckCode($phone,$area);
                }
            }
            //超过时限和没有记录
            //生成验证码
            $check_code = Common::generateCode();

            //调用短信网关发送短信
            try {
                $sms_send_record_id = Sms::send_message($area,$phone,'员工您好，感谢您对此次测试的配合。');
            } catch (Exception $e) {
                Log::error("error", array("system" => "wxw" ,"event" => "sms_check_code", 'input' =>Input::all() ,"exception" => $e));
                $response = Lang::get("error.user_sms_check_code_send_error_1003");
                break;
            }

            //记录数据库
            $data = array(
                'phone' => $phone,
                'area' => $area,
                'check_code' => $check_code,
                'created_at' => Common::num2DateTime(time()),
                'out_time_at' => Common::num2DateTime(time() + $time_out_default),
                'send_id' => $sms_send_record_id,
            );

            try {
                UserCheckCode::insCheckCode($data);
            } catch (Exception $e) {
                Log::error("error", array("system" => "wxw" ,"event" => "sms_check_code", 'input' =>Input::all() ,"exception" => $e));
                $response = Lang::get("error.user_sms_check_code_create_error_1002");
                break;
            }

            //组织返回
            $response = array(
                'code' => 0,
                'msg' => 'ok',
                'result' => array(
                    'out_time' => $time_out_default,
                    'check_code' => $check_code // todo 调试使用
                ));

        } while (false);

        Log::info("info", array("system" => "wxw" ,"event" => "sms_check_code", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
}
